package com.huluobo.a2206douyindemo.live;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.huluobo.a2206douyindemo.R;
import com.huluobo.a2206douyindemo.adapter.ChatRoomAdapter;
import com.huluobo.a2206douyindemo.adapter.GiftAdapter;
import com.huluobo.a2206douyindemo.databinding.ActivityLiveBinding;
import com.huluobo.a2206douyindemo.pay.PayActivity;
import com.huluobo.a2206douyindemo.shop.ShopActivity;
import com.huluobo.a2206douyindemo.utils.ImageUtils;
import com.huluobo.base.bean.GiftBeanResult;
import com.huluobo.base.bean.Money;
import com.huluobo.base.bean.VideoBeanResult;
import com.huluobo.base.db.AppDBUtils;
import com.huluobo.base.mvvm.BaseMVVMActivity;
import com.huluobo.base.net.Const;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;

import java.util.List;

import top.littlefogcat.danmakulib.danmaku.Danmaku;
import top.littlefogcat.danmakulib.danmaku.DanmakuManager;


public class LiveActivity extends BaseMVVMActivity<ActivityLiveBinding, LiveViewModel> {
    private VideoBeanResult.VideoBean videoBean;
    private GiftAdapter giftAdapter;
    private GiftBeanResult.GiftBean giftBean;
    private Money money;
    private ChatRoomAdapter chatRoomAdapter;

    @Override
    protected void initData() {
        viewModel.getUserMoneyByName(SPUtils.getInstance().getString(Const.PARAM_USERNAME));

        viewModel.getUserMoneySuccess.observe(this, money -> {
            this.money = money;
            binding.liveUserMoneyTv.setText("用户余额:" + money.getMoney() + "抖币");
        });

        viewModel.getUserMoneyFailed.observe(this, s -> {
            Log.i("TagA", "获取用户余额失败");
        });

        viewModel.followAuthSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoBean.setGuanzhu(1);
                binding.liveFollowBtn.setText("已关注");
                binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_black);
            }
        });

        viewModel.followAuthFailed.observe(this, s -> {
            Log.i("TagA", "关注失败" + s);
        });

        viewModel.cancelFollowSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoBean.setGuanzhu(0);
                binding.liveFollowBtn.setText("关注");
                binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red);
            }
        });

        viewModel.cancelFollowFailed.observe(this, s -> {
            Log.i("TagA", "取消关注失败" + s);
        });

        viewModel.getGiftListSuccess.observe(this, giftBeanResult -> {
            if (giftBeanResult.getCode() == 200) {
                giftAdapter.getData().clear();
                giftAdapter.getData().addAll(giftBeanResult.getData());
                giftAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(giftBeanResult.getMessage());
            }
        });

        viewModel.getGiftListFailed.observe(this, s -> {
            Log.i("TagA", "获取礼物列表失败" + s);
        });
    }

    @Override
    protected void initView() {
        videoBean = (VideoBeanResult.VideoBean) getIntent().getSerializableExtra("videoBean");
        assert videoBean != null;
        binding.liveGsyPlayer.getBackButton().setVisibility(View.GONE);
        binding.liveGsyPlayer.setUp(videoBean.getVideopath(), true, "");
//        binding.liveGsyPlayer.startPlayLogic();

        //头像
        ImageUtils.getInstance().loadCircleImage(this, videoBean.getHeadpath(), binding.liveUserIconIv);
        //作者名
        binding.liveUsernameTv.setText(videoBean.getAuthname());
        //关注状态
        binding.liveFollowBtn.setText(videoBean.getGuanzhu() == 0 ? "关注" : "已关注");
        //设置关注状态的背景
        binding.liveFollowBtn.setBackgroundResource(videoBean.getGuanzhu() == 0 ? R.drawable.shape_red :
                R.drawable.shape_black);
        //喜欢数量
        binding.liveLikeCountTv.setText(videoBean.getLike_count() + "人喜欢");
        //关注按钮的点击事件
        binding.liveFollowBtn.setOnClickListener(v -> {
            if (videoBean.getGuanzhu() == 0) {
                //未关注,触发关注接口
                viewModel.followAuth(videoBean.getAuthname());
            } else {
                //已关注,触发取消关注接口
                viewModel.cancelFollow(videoBean.getAuthname());
            }
        });
//
//        //添加点赞动画的图片资源
//        binding.liveLikeView.addLikeImages(
//                R.drawable.fav_0,
//                R.drawable.fav_1,
//                R.drawable.fav_2,
//                R.drawable.fav_3,
//                R.drawable.fav_4,
//                R.drawable.fav_5
//        );
//
//        //点击点赞按钮触发点赞动画
//        binding.liveLikeIv.setOnClickListener(v -> {
//            binding.liveLikeView.addFavor();
//        });

        binding.liveBezierView.setIds(
                new int[]{
                        R.drawable.fav_0,
                        R.drawable.fav_1,
                        R.drawable.fav_2,
                        R.drawable.fav_3,
                        R.drawable.fav_4,
                        R.drawable.fav_5,
                        R.drawable.fav_0,
                        R.drawable.fav_1,
                        R.drawable.fav_2,
                        R.drawable.fav_3,
                        R.drawable.fav_4,
                        R.drawable.fav_5
                }
        );

        binding.liveLikeIv.setOnClickListener(v -> {
            binding.liveBezierView.addFavor();
        });

        //点击弹幕按钮弹出弹幕输入布局
        binding.liveDanmuIv.setOnClickListener(v -> {
            binding.liveDanmuLayoutLll.setVisibility(View.VISIBLE);
        });

        //初始化弹幕
//        initDanmuView();

        //单击弹幕发送按钮的事件
        binding.lievDanmuSendIv.setOnClickListener(v -> {
//            sendDanmu();
            sendEasyDanmu();
        });

        //打开礼物列表
        binding.liveGiftIv.setOnClickListener(v -> {
            binding.liveGiftLayoutCl.setVisibility(View.VISIBLE);
            viewModel.getGiftList();
        });

        //关闭礼物列表
        binding.liveCloseTv.setOnClickListener(v -> {
            binding.liveGiftLayoutCl.setVisibility(View.GONE);
        });

        binding.liveGiftRv.setLayoutManager(new GridLayoutManager(this, 5));
        giftAdapter = new GiftAdapter();
        binding.liveGiftRv.setAdapter(giftAdapter);

        giftAdapter.setOnItemClickListener((adapter, view, position) -> {
//            giftBean = (GiftBeanResult.GiftBean) adapter.getData().get(position);
            giftBean = giftAdapter.getData().get(position);
            ImageUtils.getInstance().loadImage(this, giftBean.getGiftpath(), binding.liveGiftSelectIv);
            binding.liveGiftSelectTv.setText(giftBean.getGiftname());
        });

        //发送礼物
        binding.liveGiftSendBtn.setOnClickListener(v -> {
            sendGift();
        });

        binding.livePayBtn.setOnClickListener(v -> {
            Intent intent = new Intent(this, PayActivity.class);
            startActivity(intent);
        });

        //聊天框展示
        binding.liveChatTv.setOnClickListener(v -> {
            binding.liveChatLayoutLl.setVisibility(View.VISIBLE);
        });

        //聊天室RV初始化
        binding.liveChatRv.setLayoutManager(new LinearLayoutManager(this));
        chatRoomAdapter = new ChatRoomAdapter();
        binding.liveChatRv.setAdapter(chatRoomAdapter);

        //聊天室的发送按钮点击事件
        binding.lievChatSendIv.setOnClickListener(v -> {
//            String msg = binding.liveChatInputEt.getText()
//            .toString();
////            if (msg.isEmpty()) {
////                ToastUtils.showLong("请输入聊天内容");
////                return;
////            }
////            String username = SPUtils.getInstance().getString(Const.PARAM_USERNAME);
////            MessageEntity message = new MessageEntity(username, msg);
////            chatRoomAdapter.getData().add(message);
////            chatRoomAdapter.notifyDataSetChanged();
////            binding.liveChatRv.scrollToPosition(chatRoomAdapter.getData().size() - 1);
////            binding.liveChatInputEt.setText("");
////            binding.liveChatLayoutLl.setVisibility(View.GONE);
            sendEMMessage(Const.CHAT_ROOM_ID, binding.liveChatInputEt.getText().toString());
        });

        //初始化聊天室
        initChatRoom();

        //小黄车跳转事件
        binding.liveCartIv.setOnClickListener(v -> {
            startActivity(new Intent(this, ShopActivity.class));
        });
    }

    //发送聊天室消息
    private void sendEMMessage(String chatRoomId, String content) {
        //构建一条消息
        EMMessage emMessage = EMMessage.createTextSendMessage(content, chatRoomId);
        //设置消息的发送类型,3种类型,单聊,群聊,聊天室
        emMessage.setChatType(EMMessage.ChatType.ChatRoom);
        //构建消息体,填入聊天内容
        emMessage.setBody(new EMTextMessageBody(content));
        //把消息发送到服务器
        EMClient.getInstance().chatManager().sendMessage(emMessage);
        //设置消息状态监听
        emMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(() -> {
                    MessageEntity message = new MessageEntity(SPUtils.getInstance().getString(Const.PARAM_USERNAME),
                            content);
                    chatRoomAdapter.getData().add(message);
                    chatRoomAdapter.notifyDataSetChanged();
                    binding.liveChatRv.scrollToPosition(chatRoomAdapter.getData().size() - 1);
                    binding.liveChatInputEt.setText("");
                    binding.liveChatLayoutLl.setVisibility(View.GONE);
                });
            }

            @Override
            public void onError(int code, String error) {
                Log.i("TagA", "发送消息失败:" + error + "code:" + code);
            }
        });

    }

    //初始化聊天室
    private void initChatRoom() {
        //消息监听器,当接收到消息时添加数据源
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        //聊天室监听器,主要监听聊天室的状态,比如有人进入,有人退出
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(emChatRoomChangeListener);
        //加入聊天室
        EMClient.getInstance().chatroomManager().joinChatRoom(Const.CHAT_ROOM_ID, new EMValueCallBack<EMChatRoom>() {
            @Override
            public void onSuccess(EMChatRoom value) {
                Log.i("TagA", "加入聊天室成功");
            }

            @Override
            public void onError(int error, String errorMsg) {
                Log.i("TagA", "加入聊天室失败:" + errorMsg + ",code:" + error);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatroomManager().leaveChatRoom(Const.CHAT_ROOM_ID);
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        EMClient.getInstance().chatroomManager().removeChatRoomListener(emChatRoomChangeListener);
    }

    //接收消息监听器
    private EMMessageListener messageListener = messages -> {
        runOnUiThread(() -> {
            for (int i = 0; i < messages.size(); i++) {
                MessageEntity message = new MessageEntity(
                        messages.get(i).getUserName(),
                        ((EMTextMessageBody) messages.get(i).getBody()).getMessage()
                );
                chatRoomAdapter.getData().add(message);
                chatRoomAdapter.notifyDataSetChanged();
            }
        });
    };

    //聊天室状态改变的监听器
    private EMChatRoomChangeListener emChatRoomChangeListener = new EMChatRoomChangeListener() {
        @Override
        public void onChatRoomDestroyed(String roomId, String roomName) {

        }

        @Override
        public void onMemberJoined(String roomId, String participant) {
            runOnUiThread(() -> {
                MessageEntity message = new MessageEntity("系统",
                        participant + "加入直播");
                chatRoomAdapter.getData().add(message);
                chatRoomAdapter.notifyDataSetChanged();
            });
        }

        @Override
        public void onMemberExited(String roomId, String roomName, String participant) {
            runOnUiThread(() -> {
                MessageEntity message = new MessageEntity("系统",
                        participant + "退出直播");
                chatRoomAdapter.getData().add(message);
                chatRoomAdapter.notifyDataSetChanged();
            });
        }

        @Override
        public void onRemovedFromChatRoom(int reason, String roomId, String roomName, String participant) {

        }

        @Override
        public void onMuteListAdded(String chatRoomId, List<String> mutes, long expireTime) {

        }

        @Override
        public void onMuteListRemoved(String chatRoomId, List<String> mutes) {

        }

        @Override
        public void onWhiteListAdded(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onWhiteListRemoved(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onAllMemberMuteStateChanged(String chatRoomId, boolean isMuted) {

        }

        @Override
        public void onAdminAdded(String chatRoomId, String admin) {

        }

        @Override
        public void onAdminRemoved(String chatRoomId, String admin) {

        }

        @Override
        public void onOwnerChanged(String chatRoomId, String newOwner, String oldOwner) {

        }

        @Override
        public void onAnnouncementChanged(String chatRoomId, String announcement) {

        }
    };

    //发送礼物的方法
    private void sendGift() {
        //拿到用户余额(查询成功会给money赋值)
        //扣款(检查用户余额是否充足,充足->余额扣款,更新UI,更新数据库中的新余额)
        //不充足,弹吐司提示充值
        if (giftBean == null && money == null) {
            ToastUtils.showLong("请选择礼物,或者余额查询失败");
            return;
        }

        //判断余额是否充足,余额是否小于礼物价格
        if (money.getMoney() < giftBean.getPrice()) {
            ToastUtils.showLong("余额不足,请充值");
            return;
        }

        float newMoney = money.getMoney() - giftBean.getPrice();
        //更新UI
        binding.liveUserMoneyTv.setText("余额:" + newMoney + "抖币");
        //保存新余额到数据库
        money.setMoney(newMoney);
        viewModel.updateUserMoney(money);

        //构建一个ImageView,承载礼物动画
        ImageView giftView = new ImageView(this);
        //直接newView,没有属性,也没有宽高,都需要设置一个宽高才能显示
        //宽高无法直接同过view去set,需要一个LayoutParams来设置
        //这个View在哪一个Layout上,就是用哪钟Layout的Params
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(200, 200);
        //给view设置宽高
        giftView.setLayoutParams(params);

        //通过最大布局来动态添加一个view
        binding.liveRootCl.addView(giftView);
        //给imageView添加图片资源
        ImageUtils.getInstance().loadImage(this, giftBean.getGiftpath(), giftView);

        //展示礼物动画
        //获取最大Layout的宽高
        float screenWidth = (float) binding.liveRootCl.getMeasuredWidth();
        float screenHeight = (float) binding.liveRootCl.getMeasuredHeight();

        ObjectAnimator translationY = ObjectAnimator.ofFloat(giftView, "translationY", screenHeight, screenHeight / 2
                , screenHeight / 5, screenHeight / 3, screenHeight / 2);

        ObjectAnimator translationX = ObjectAnimator.ofFloat(giftView, "translationX", screenWidth / 2,
                screenWidth / 5, screenWidth / 2, screenWidth / 3 * 2, screenWidth / 2);

        ObjectAnimator rotation = ObjectAnimator.ofFloat(giftView, "rotation", 0, 1800);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(giftView, "scaleX", 1, 2, 1, 3, 1, 2, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(giftView, "scaleY", 1, 2, 1, 3, 1, 2, 1);

        AnimatorSet set = new AnimatorSet();
        set.setDuration(3000);
        set.setInterpolator(new AccelerateDecelerateInterpolator());
        set.playTogether(translationY, translationX, rotation, scaleY, scaleX);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                //动画开始时,关闭礼物列表
                binding.liveGiftLayoutCl.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //动画结束时,移除掉礼物view
                binding.liveRootCl.removeView(giftView);
            }
        });

        //开启动画
        set.start();
    }

    private void sendEasyDanmu() {
        String danmuString = binding.liveDanmuInputEt.getText().toString();

        if (danmuString.isEmpty()) {
            ToastUtils.showLong("弹幕不能为空");
            return;
        }

        //设置简单弹幕
        Danmaku danmaku = new Danmaku();
        danmaku.text = danmuString;
        danmaku.size = 40;
        DanmakuManager.getInstance()
                .init(this, binding.liveDanmuView);
        DanmakuManager.getInstance().send(danmaku);

        binding.liveDanmuInputEt.setText("");
        binding.liveDanmuLayoutLll.setVisibility(View.GONE);
    }

    //发送弹幕
//    private void sendDanmu() {
//        //获取弹幕内容
//        String danmuString = binding.liveDanmuInputEt.getText().toString();
//        if (danmuString.isEmpty()) {
//            ToastUtils.showLong("请输入弹幕内容,不能为空");
//            return;
//        }
//
//        //清理弹幕
//        binding.liveDanmuView.clear();
//        binding.liveDanmuView.removeAllDanmakus(true);
//
//        //创建弹幕实体类
//        BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);//设置弹幕方向
//        danmaku.text = danmuString;//弹幕文本
//        danmaku.textSize = 30;
//        danmaku.textColor = Color.WHITE;
//        danmaku.padding = 10;
//        danmaku.setTime(800);
//
//        //添加弹幕到弹幕VIew中
//        binding.liveDanmuView.addDanmaku(danmaku);
//        binding.liveDanmuView.start();//启动弹幕
//
//        //发送弹幕之后,需要清空弹幕输入框,和隐藏弹幕输入布局
//        binding.liveDanmuInputEt.postDelayed(() -> {
//            binding.liveDanmuInputEt.setText("");
//            binding.liveDanmuLayoutLll.setVisibility(View.GONE);
//        }, 300);
//    }

    //初始化弹幕时需要一个弹幕的上下文,先声明
//    private DanmakuContext danmakuContext;

//    private void initDanmuView() {
//        //1.清理弹幕的缓存
//        binding.liveDanmuView.enableDanmakuDrawingCache(false);
//        //清空弹幕view
//        binding.liveDanmuView.clear();
//        //移除所有弹幕
//        binding.liveDanmuView.removeAllDanmakus(true);
//
//        //2.弹幕上下文
//        danmakuContext = DanmakuContext.create();
//        //3.准备弹幕
//        binding.liveDanmuView.prepare(new BaseDanmakuParser() {
//            @Override
//            protected IDanmakus parse() {
//                return new Danmakus();
//            }
//        }, danmakuContext);
//    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live;
    }
}